from django import forms
from rbac import models
class MultiPermissionsForm(forms.Form):


    id=forms.IntegerField(widget=forms.HiddenInput(),required=False)
    title=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}),required=True)
    url=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    name=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    menu_id=forms.ChoiceField(choices=[(None,'-----'),],widget=forms.Select(attrs={'class':'form-control'}),required=False)
    parent_id=forms.ChoiceField(choices=[(None,'-----'),],widget=forms.Select(attrs={'class':'form-control'}),required=False)

    def __init__(self,*args,**kwargs):
        super(MultiPermissionsForm,self).__init__(*args,**kwargs)
        self.fields['menu_id'].choices+=models.Menu.objects.values_list('id','title')
        self.fields['parent_id'].choices+=models.Permission.objects.filter(parent__isnull=True).exclude(menu__isnull=True).values_list('id','title')

    def clean_parent_id(self):
        menu_id=self.cleaned_data.get('menu_id')
        parent_id=self.cleaned_data.get('parent_id')
        if menu_id and parent_id:
            raise forms.ValidationError('菜单和根权限只能选一个')
        else:
            return parent_id


class PermissionModelForm(forms.ModelForm):
    class Meta:
        model=models.Permission
        fields="__all__"
        widgets={
            'title':forms.TextInput(attrs={'class':'form-control','placeholder':'请输入权限名称'}),
            'url':forms.TextInput(attrs={'class':'form-control','placeholder':'请输入url'}),
            'name':forms.TextInput(attrs={'class':'form-control','placeholder':'请输入url别名'}),
            'parent':forms.Select(attrs={'class':'form-control','placeholder':'请输入父级权限'}),
            'menu':forms.Select(attrs={'class':'form-control','placeholder':'请选择菜单'})
        }
        help_texts={
            'parent':'父级权限，无法作为菜单的权限才需要选择',
            'menu':'选中，表示该权限可以作为菜单，否则不能作为菜单'
        }
        # error_messages={
        #     'title':{"required":'aas'}
        # }
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
    def clean(self):
        menu=self.cleaned_data.get('menu')
        parent=self.cleaned_data.get('parent')
        if menu and parent:
            self.add_error('menu','菜单和权限只能同时选一个')